import React, { useState } from 'react';
import { getLocale } from 'umi';
import { Select } from 'antd';
import { IntlProvider } from 'react-intl';
import Consumer from './_components/Consumer';

export default props => {
  const {
    locales = {
      'zh-CN': {
        name: '简体中文',
        data: {
          记住我: '记住我',
        },
      },
      'en-US': {
        name: 'English',
        data: {
          记住我: 'Remember me',
        },
      },
    },
    defaultCurrentLocale,
    addonBefore,
    ...rest
  } = props;

  const [currentLocale, setCurrentLocale] = useState(defaultCurrentLocale || getLocale());

  return (
    <>
      {(addonBefore && addonBefore({ locales, currentLocale, setCurrentLocale })) || (
        <Select
          value={currentLocale}
          onChange={newCurrentLocale => {
            setCurrentLocale(newCurrentLocale);
          }}
          style={{ display: 'block', width: 120, marginBottom: 10 }}
          {
            // eslint-disable-next-line
            ...props.select
          }
        >
          {Object.keys(locales).map(item => (
            <Select.Option value={item}>{locales[item]?.name}</Select.Option>
          ))}
        </Select>
      )}

      <IntlProvider locale={currentLocale} messages={locales[currentLocale]?.data}>
        <Consumer {...rest} />
      </IntlProvider>
    </>
  );
};
